package com.rgs.base.redis.service.impl;

import com.rgs.base.redis.service.GlobalAtomService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.function.Supplier;

/**
 * @author Ren Gaoshuai
 * @ClassName RedisGlobalAtomServiceImpl
 * 通用redis自增器
 * @date 2021-12-24 16:38
 **/
@Service
public class RedisGlobalAtomServiceImpl implements GlobalAtomService {

    @Resource
    RedisTemplate redisTemplate;

    @Override
    public Long incrementLong(String key, long delta, long def) {
        if (!redisTemplate.hasKey(key)) {
            if (redisTemplate.opsForValue().setIfAbsent(key, def)) {
                return def;
            }
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    @Override
    public Long incrementLong(String key, long delta, Supplier<Long> supplier) {
        return this.incrementLong(key, delta, supplier.get());
    }

    @Override
    public Long incrementLong(String key, Supplier<Long> supplier) {
        return this.incrementLong(key, 1, supplier.get());
    }

    @Override
    public Long incrementLong(String key) {
        return this.incrementLong(key, 1, 0);
    }
}
